package com.yuan.member.producer;


import cn.common.constant.RabbitConstants;
import cn.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.UUID;

@Component
@Slf4j
public class RabbitMqProducer {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitMqProducer(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate  = rabbitTemplate;
        initCallbacks();
    }

    private void initCallbacks() {
        // 发送到Exchange确认回调
        rabbitTemplate.setConfirmCallback((correlation,  ack, cause) -> {

            if (correlation != null) {
                log.info("Correlation  ID: {}", correlation.getId());
                if (!ack) {
                    log.error(" 消息未到达Exchange: {}", cause);
                }
            }
        });

        // 路由到Queue失败回调（需配置mandatory=true）
        rabbitTemplate.setReturnsCallback(returned  -> {
            log.error(" 消息路由失败: {}", returned.getMessage());
            log.error("Exchange:  {}, RoutingKey: {}", returned.getExchange(),  returned.getRoutingKey());
        });
    }

    public void putRegister(String content) {
        try {
            CorrelationData correlation = new CorrelationData(UUID.randomUUID().toString());
            // 增强消息属性
//            MessagePostProcessor processor = message -> {
//                message.getMessageProperties()
//                        .setDeliveryMode(MessageDeliveryMode.PERSISTENT); // 持久化
//                message.getMessageProperties()
//                        .setHeader("TIMESTAMP", System.currentTimeMillis());
//                return message;
//            }
            rabbitTemplate.convertAndSend(
                    RabbitConstants.EXCHANGE_NAME,
                    RabbitConstants.ROUTING_KEY,
                    content,
                   // processor,
                    correlation
            );

            log.info(" 消息已发送，ID: {}", correlation.getId());
        } catch (Exception e) {
            log.error(" 消息发送异常", e);
            throw new BusinessException( "消息发送失败");
        }
    }

    public void putWalletPool(String content) {
        try {
            CorrelationData correlation = new CorrelationData(UUID.randomUUID().toString());
            rabbitTemplate.convertAndSend(
                    RabbitConstants.EXCHANGE_WALLER,
                    RabbitConstants.ROUTING_KEY_WALLER,
                    content,
                    correlation
            );
            log.info(" 消息已发送，ID: {}", correlation.getId());
        } catch (RuntimeException e) {
            log.error(" 消息发送异常", e);
            throw new BusinessException( "消息发送失败");
        }
    }
}
